﻿/*
 * *******************************************************
 *
 * 作者：HZY
 *
 * 开源地址：https://gitee.com/hzy6
 *
 * *******************************************************
 */
namespace HZY.Framework.Core;

/// <summary>
/// AspNetCore 服务启动程序
/// </summary>
public static class HzyApplication
{
    /// <summary>
    /// 启动 AspNetCore 应用程序
    /// </summary>
    /// <typeparam name="TStartupModule"></typeparam>
    /// <param name="args"></param>
    /// <param name="options"></param>
    /// <returns></returns>
    public static async Task RunAsync<TStartupModule>(string[] args,
        Action<AppOptions>? options = null)
        where TStartupModule : IStartupModule
    {
        var webApplicationBuilder = WebApplication.CreateBuilder(args);

        // 打印启动信息
        Console.WriteLine(@$"

$$\   $$\ $$$$$$$$\ $$\     $$\ 
$$ |  $$ |\____$$  |\$$\   $$  |
$$ |  $$ |    $$  /  \$$\ $$  / 
$$$$$$$$ |   $$  /    \$$$$  /  
$$  __$$ |  $$  /      \$$  /   
$$ |  $$ | $$  /        $$ |    
$$ |  $$ |$$$$$$$$\     $$ |    
\__|  \__|\________|    \__|    

项目 {webApplicationBuilder.Environment.ApplicationName} 启动! -- {DateTime.Now:yyyy-MM-dd HH:mm:ss}

");

        // 加入 hzy framework
        webApplicationBuilder.AddHzyFramework<TStartupModule>(options);

        // 构建
        var webApplication = webApplicationBuilder.Build();

        // 设置host
        AopMoAttribute.SetHost(webApplication);

        // 设置服务提供者
        webApplication.Use(async (context, next) =>
        {
            AopMoAttribute.SetServiceProvider(context.RequestServices);
            await next?.Invoke(context)!;
        });

        // 启动 app
        await webApplication.StartHzyFrameworkAsync();
    }

    /// <summary>
    /// 启动 AspNetCore 应用程序
    /// </summary>
    /// <param name="args"></param>
    /// <param name="options"></param>
    /// <typeparam name="TStartupModule"></typeparam>
    public static void Run<TStartupModule>(string[] args,
        Action<AppOptions>? options = null)
        where TStartupModule : IStartupModule
    {
        RunAsync<TStartupModule>(args, options).Wait();
    }
}